<!DOCTYPE html>
<html>
  <head>
    <title>SQL Query Console</title>
    <link href="../styles.css" rel="stylesheet">
  </head>
  <body>
    <header>
      <strong>Query Console</strong>
      <span style="margin-right: 0.5em;"></span>
        Connector:
        <select id="connector">
          <option value="socket">Socket</option>
          <option value="rest">REST</option>
          <option value="wasm" selected>WASM</option>
        </select>
      </span>
      <span style="margin-right: 0.5em;"></span>
        Mode:
        <select id="mode">
          <option value="query" selected>Query</option>
          <option value="exec">Exec</option>
        </select>
      </span>
    </header>
    <textarea style="width: 98%; height: 140px;" id="input"></textarea>
    <br/>
    <button id="submit">Query</button>
    <br/>
    <div id="output"></div>
<script type="module">
  import { setDatabaseConnector, coordinator, vg } from '../setup.js';
  const tableName = 'query_result';

  const input = document.querySelector('#input');
  const output = document.querySelector('#output');
  const submit = document.querySelector('#submit');
  const exec = document.querySelector('#exec');
  const menu = document.querySelector('#connector');
  const mode = document.querySelector('#mode');

  function disable() {
    input.setAttribute('disabled', true);
    submit.setAttribute('disabled', true);
  }

  function enable() {
    input.removeAttribute('disabled');
    submit.removeAttribute('disabled');
  }

  menu.addEventListener('change', () => setDatabaseConnector(menu.value));

  submit.addEventListener('click', async () => {
    disable();
    if (mode.value === 'exec') {
      await coordinator.exec(`${input.value}`);
      output.replaceChildren();
    } else {
      await coordinator().exec(
        `DROP TABLE IF EXISTS ${tableName};
        CREATE TABLE ${tableName} AS ${input.value}`
      );
      coordinator.clear({ catalog: true });
      output.replaceChildren(vg.table({ from: tableName, height: 500 }));
    }
    enable();
  });
</script>
  </body>
</html>
